﻿///***************************************************************
/// 시  스  템 : Updms.Crd
/// 단위시스템 : CRD
/// 계      층 : Presentation Layer
/// 프로그램명 : Crd2011r
/// 파  일  명 : Crd2011r.aspx.cs
/// 설      명 : 카드사용챠트 - (바, 파이차트)
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-07-25 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.Dac;
using Updms.Crd.Exe;


namespace Updms.Crd
{
	public partial class Crd2011r : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Crd2011r";
		public static readonly string gs_path_info = "/updms/Crd/" + PID + ".aspx";

		Global global = new Global();
		
		//검색
		protected string kw1 = "";	// card_cd
		protected string kw2 = "";	// from_dt
		protected string kw3 = "";	// to_dt
		protected string kw4 = "";	// exc_sys_id
		protected string kw5 = "";	// exc_prefix

		//메뉴 선택값
		protected string gs_sm = "";

		// 페이지모드
		private string gs_page_mode = "";

		//합계
		decimal ld_total = 0;
		decimal ld_mass = 0;
		decimal ld_cash = 0;
		decimal ld_ins = 0;

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetCardInfo();
			SetYearMonth();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion	

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			
			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_card_cd.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_card_cd.SelectedValue = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = ddl_search_from_year.SelectedValue + "-" + ddl_search_from_month.SelectedValue;
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						ddl_search_from_year.SelectedValue = kw2.Substring(0, 4).ToString();
						ddl_search_from_month.SelectedValue = kw2.Substring(5, 2).ToString();
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						kw3 = ddl_search_to_year.SelectedValue + "-" + ddl_search_to_month.SelectedValue;
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						ddl_search_to_year.SelectedValue = kw3.Substring(0, 4).ToString();
						ddl_search_to_month.SelectedValue = kw3.Substring(5, 2).ToString();
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_card_cd.SelectedValue;
					kw2 = ddl_search_from_year.SelectedValue + "-" + ddl_search_from_month.SelectedValue;
					kw3 = ddl_search_to_year.SelectedValue + "-" + ddl_search_to_month.SelectedValue;
					break;
			}

			if (cb_support_yn.Checked)
			{
				kw4 = "CRD";
				kw5 = "AG";
			}
			else
			{
				kw4 = "";
				kw5 = "";
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw1 = ddl_search_card_cd.SelectedItem.Text;
			string ls_kw2 = ddl_search_from_year.SelectedValue + "-" + ddl_search_from_month.SelectedValue;
			string ls_kw3 = ddl_search_to_year.SelectedValue + "-" + ddl_search_to_month.SelectedValue;
			string ls_kw45 = cb_support_yn.Checked ? "Y" : "N";
			lbl_search_keyword.Text = ls_kw1 + " / " + ls_kw2 + " / " + ls_kw3 + " / " + ls_kw45;

			// 파이그래프용
			lbl_label.Text = ls_kw1 + " / " + h_paymnt_dt.Value;

			lbl_label_detail.Text = ls_kw1 + " / " + h_paymnt_dt.Value + " / " + h_account_nm.Value;
		}

		#endregion

		#region 마스터 Method (SetYearMonth)

		// 검색조건의 년월설정
		private void SetYearMonth()
		{
			ddl_search_from_year.Items.Clear();
			ddl_search_to_year.Items.Clear();

			//현재년도 기준으로 ±2년 -> SEARCH_Y_MIN년부터 현재+1년
			int li_f_year = Convert.ToInt32(SEARCH_Y_MIN);
			int li_t_year = Convert.ToInt32(DateUtil.GetYearEx(1, "yyyy"));
			for (int i = li_f_year; i <= li_t_year; i++)
			{
				string ls_year = i.ToString();
				ddl_search_from_year.Items.Add(new ListItem(ls_year, ls_year));
				ddl_search_to_year.Items.Add(new ListItem(ls_year, ls_year));
			}

			SetYearMonth(-12);
		}

		// 검색조건의 년월설정 - 기간지정
		private void SetYearMonth(int li_term)
		{
			ddl_search_from_year.SelectedValue = DateUtil.GetMonthEx(li_term, "yyyy"); //x개월전년도
			ddl_search_from_month.SelectedValue = DateUtil.GetMonthEx(li_term, "MM"); //x개월전월
			ddl_search_to_year.SelectedValue = DateUtil.GetYearEx(0, "yyyy"); // 현재년도
			ddl_search_to_month.SelectedValue = DateUtil.GetMonthEx(0, "MM"); // 현재월
		}

		#endregion

		#region 디테일 Method (SetCardInfo)

		// 카드정보에서 카드정보를 가져와서 ddl_search_card_cd에 채운다.
		private void SetCardInfo()
		{
			DataSet lo_ds = new DataSet();
			Crd1010m_NT _Crd1010m_NT = new Crd1010m_NT();

			lo_ds.Merge(_Crd1010m_NT.GetCardInfoList("Y"));

			ddl_search_card_cd.Items.Clear();
			ddl_search_card_cd.DataSource = lo_ds;
			ddl_search_card_cd.DataMember = "UPDMS_CRD_INFO";
			ddl_search_card_cd.DataTextField = "Card_Nm";
			ddl_search_card_cd.DataValueField = "Card_Cd";
			ddl_search_card_cd.DataBind();
		}

		#endregion

		#region 리스트 (SetTotalAmtListByBizDiv, SetMonthlyAmtListByAccount, SetMonthlyAmtDetailByAccount)

		//결제구분별 카드사용총액 리스트 - 바챠트 밑
		private void SetTotalAmtListByBizDiv()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_from_dt", typeof(string), kw2);
			lo_dp.AddProperty("ls_to_dt", typeof(string), kw3);
			lo_dp.AddProperty("ls_exc_sys_id", typeof(string), kw4);
			lo_dp.AddProperty("ls_exc_prefix", typeof(string), kw5);

			using (Crd2011r_NT _Crd2011r_NT = new Crd2011r_NT())
			{
				lo_ds.Merge(_Crd2011r_NT.GetTotalAmtListByBizDiv(lo_dp));
			}
			
			int li_count = DataSetUtil.GetRowCount(lo_ds, "UPDMS_CRD_REPORT");

			GridView1.DataSource = lo_ds;
			GridView1.DataBind();				

			//결과출력(키워드, 검색행수)
			ShowKeywordLabel();
		}

		//계정별 카드사용총액 리스트 - 파이챠트 밑
		private void SetMonthlyAmtListByAccount(string ls_card_cd, string ls_paymnt_dt)
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), ls_card_cd);
			lo_dp.AddProperty("ls_paymnt_dt", typeof(string), ls_paymnt_dt);
			lo_dp.AddProperty("ls_exc_sys_id", typeof(string), kw4);
			lo_dp.AddProperty("ls_exc_prefix", typeof(string), kw5);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Crd2011r_NT _Crd2011r_NT = new Crd2011r_NT())
			{
				lo_ds.Merge(_Crd2011r_NT.GetMonthlyAmtListByAccount(lo_dp));
			}
			GridView2.DataSource = lo_ds;
			GridView2.DataBind();
		}

		//계정별 카드사용 상세리스트
		private void SetMonthlyAmtDetailByAccount(string ls_card_cd, string ls_paymnt_dt, string ls_account)
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), ls_card_cd);
			lo_dp.AddProperty("ls_paymnt_dt", typeof(string), ls_paymnt_dt);
			lo_dp.AddProperty("ls_account", typeof(string), ls_account);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Crd2011r_NT _Crd2011r_NT = new Crd2011r_NT())
			{
				lo_ds.Merge(_Crd2011r_NT.GetMonthlyAmtDetailByAccount(lo_dp));
			}
			GridView3.DataSource = lo_ds;
			GridView3.DataBind();
		}

		#endregion

		#region 챠트 (DrawTotalAmtListByBizDiv, DrawMonthlyAmtListByAccount)

		//결제구분별 카드사용총액 챠트 - 바
		private void DrawTotalAmtListByBizDiv()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//초기화
			chart_line_total.Data.Clear();
			
			//시리즈 갯수
			chart_line_total.Data.Series = 3;			

			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_from_dt", typeof(string), kw2);
			lo_dp.AddProperty("ls_to_dt", typeof(string), kw3);
			lo_dp.AddProperty("ls_exc_sys_id", typeof(string), kw4);
			lo_dp.AddProperty("ls_exc_prefix", typeof(string), kw5);

			using (Crd2011r_NT _Crd2011r_NT = new Crd2011r_NT())
			{
				lo_ds.Merge(_Crd2011r_NT.GetTotalAmtListByBizDiv(lo_dp));
			}
			
			int li_count = DataSetUtil.GetRowCount(lo_ds, "UPDMS_CRD_REPORT");

			for (int i = 0; i < li_count; i++)
			{
				//수동으로 데이터 바인딩
				int li_mass = DataSetUtil.GetFldInt(lo_ds, "UPDMS_CRD_REPORT", i, "Total_Mass");
				int li_cash = DataSetUtil.GetFldInt(lo_ds, "UPDMS_CRD_REPORT", i, "Total_Cash");
				int li_ins = DataSetUtil.GetFldInt(lo_ds, "UPDMS_CRD_REPORT", i, "Total_Ins");

				chart_line_total.Data[0, i] = li_mass; // 일시불
				chart_line_total.Data[1, i] = li_cash; // 현금서비스
				chart_line_total.Data[2, i] = li_ins;  // 할부

				//X축 라벨링
				chart_line_total.AxisX.Labels[i] = "'" + DataSetUtil.GetFldStr(lo_ds, "UPDMS_CRD_REPORT", i, "Paymnt_Dt").Substring(2, 5).Replace("-", ".");
			}
		}

		//계정별 카드사용총액 챠트 - 파이
		private void DrawMonthlyAmtListByAccount(string ls_card_cd, string ls_paymnt_dt)
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//초기화
			chart_pie_detail.Data.Clear();

			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), ls_card_cd);
			lo_dp.AddProperty("ls_paymnt_dt", typeof(string), ls_paymnt_dt);
			lo_dp.AddProperty("ls_exc_sys_id", typeof(string), kw4);
			lo_dp.AddProperty("ls_exc_prefix", typeof(string), kw5);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Crd2011r_NT _Crd2011r_NT = new Crd2011r_NT())
			{
				lo_ds.Merge(_Crd2011r_NT.GetMonthlyAmtListByAccount(lo_dp));
			}
			
			int li_count = DataSetUtil.GetRowCount(lo_ds, "UPDMS_CRD_REPORT");

			for (int i = 0; i < li_count; i++)
			{
				//수동으로 데이터 바인딩
				chart_pie_detail.Data[0, i] = DataSetUtil.GetFldInt(lo_ds, "UPDMS_CRD_REPORT", i, "Total");

				//X축 라벨링
				chart_pie_detail.AxisX.Labels[i] = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CRD_REPORT", i, "Account_Nm");
			}
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":		// 처음 페이지로드시
					table_detail.Visible = false;
					table_chart_line_total.Visible = false;
					table_chart_pie_detail.Visible = false;
					table_dg1.Visible = false;
					table_dg2.Visible = false;
					table_dg3.Visible = false;

					break;
				case "R":	// 검색버튼 클릭시
					table_detail.Visible = true;
					table_chart_line_total.Visible = true;
					table_chart_pie_detail.Visible = false;
					table_dg1.Visible = true;
					table_dg2.Visible = false;
					table_dg3.Visible = false;
					break;
				case "PIE":	// 파이 버튼 클릭시
					table_detail.Visible = true;
					table_chart_line_total.Visible = true;
					table_chart_pie_detail.Visible = true;
					table_dg1.Visible = true;
					table_dg2.Visible = true;
					table_dg3.Visible = false;
					break;
				case "DTL":	// 지출구분 클릭시
					table_detail.Visible = true;
					table_chart_line_total.Visible = true;
					table_chart_pie_detail.Visible = true;
					table_dg1.Visible = true;
					table_dg2.Visible = true;
					table_dg3.Visible = true;
					break;
			}
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//결제구분별 카드사용총액 리스트
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				//번호
				e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();
				
				//합계
				ld_total += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total_All"));
				ld_mass += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total_Mass"));
				ld_cash += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total_Cash"));
				ld_ins += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total_Ins"));
			}
			
			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Text = "Total";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[0].ColumnSpan = 2;
				e.Row.Cells[1].Visible = false;
				e.Row.Cells[2].Text = ld_total.ToString("#,###,##0");
				e.Row.Cells[2].Attributes.Add("class", "money");
				e.Row.Cells[3].Text = ld_mass.ToString("#,###,##0");
				e.Row.Cells[3].Attributes.Add("class", "money");
				e.Row.Cells[4].Text = ld_cash.ToString("#,###,##0");
				e.Row.Cells[4].Attributes.Add("class", "money");
				e.Row.Cells[5].Text = ld_ins.ToString("#,###,##0");
				e.Row.Cells[5].Attributes.Add("class", "money");
				e.Row.Cells[6].Text = "";
				e.Row.Cells[6].Attributes.Add("class", "none");
				e.Row.Cells[7].Text = "";
				e.Row.Cells[7].Attributes.Add("class", "none");
			}
		}

		//계정별 카드사용총액 리스트
		protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				//번호
				e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();				
			}
		}

		//계정별 카드사용 상세리스트
		protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);
			}

			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView3);
			sGv.RowSpanGridView(GridView3, 0);	//구분
			sGv.RowSpanGridView(GridView3, 1);	//계정
		}

		#endregion

		#region 버튼이벤트

		//6개월
		protected void sbtn_6_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-5);
		}

		//12개월
		protected void sbtn_12_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-12);
		}

		//전체
		protected void sbtn_all_m_Click(object sender, EventArgs e)
		{
			ddl_search_from_year.SelectedIndex = 0;
			ddl_search_from_month.SelectedIndex = 0;
			ddl_search_to_year.SelectedIndex = ddl_search_to_year.Items.Count - 1;
			ddl_search_to_month.SelectedIndex = ddl_search_to_month.Items.Count - 1;
		}

		//챠트
		protected void ibtn_chart_Click(object sender, EventArgs e)
		{
			gs_page_mode = "R";
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			
			DrawTotalAmtListByBizDiv();	//바챠트
			SetTotalAmtListByBizDiv();	//바리스트
		}

		//바챠트에서 파이아이콘 클릭
		protected void lbtn_pie_chart_Click(object sender, EventArgs e)
		{
			gs_page_mode = "PIE";

			SetSearchParameter();
			ShowKeywordLabel();
			
			//클릭한 Row를 굵게
			SMGridView sGv = new SMGridView(this.Page, ref GridView1);
			sGv.BoldRowGridView(GridView1, 1, h_paymnt_dt.Value);
			
			DrawMonthlyAmtListByAccount(h_card_cd.Value, h_paymnt_dt.Value);	//파이챠트
			SetMonthlyAmtListByAccount(h_card_cd.Value, h_paymnt_dt.Value);	//파이리스트
		}

		//파이챠트에서 지출구분 클릭
		protected void lbtn_view_detail_Click(object sender, EventArgs e)
		{
			gs_page_mode = "DTL";

			SetSearchParameter();
			ShowKeywordLabel();
			
			//클릭한 Row를 굵게
			SMGridView sGv = new SMGridView(this.Page, ref GridView2);
			sGv.BoldRowGridView(GridView2, "Account_Nm", h_account_nm.Value);
			
			SetMonthlyAmtDetailByAccount(h_card_cd.Value, h_paymnt_dt.Value, h_account.Value);	//상세리스트
		}
		
		#endregion
	}
}
